﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.Script.Serialization;

namespace SocialWebpart
{
    [ToolboxItemAttribute(false)]
    public partial class SocialWebpart : System.Web.UI.WebControls.WebParts.WebPart
    {

        #region FaceBook Private Variables
        /// <summary>
        /// Face Book Authorization token for the App.
        /// </summary>
        private string facebookTokenCode = string.Empty;

        /// <summary>
        /// User for whose feed will be displayed on the Facebook tab.
        /// </summary>
        private string facebookUserId = string.Empty;

        /// <summary>
        /// Number of posts to retrieve for from the User's wall post.
        /// </summary>
        private int facebookPostsCount = 10;
        #endregion

        #region Twitter Private Variables

        /// <summary>
        /// User for whose tweets will be displayed on the Twitter tab.
        /// </summary>
        private string twitterUserId = string.Empty;

        /// <summary>
        /// Number of posts to retrieve for from the User's tweets.
        /// </summary>
        private int twitterPostsCount = 10;

        /// <summary>
        /// Application/Consumer Key
        /// </summary>
        private string apiOauthToken = string.Empty;

        /// <summary>
        /// Application/Consumer Secret Key
        /// </summary>
        private string apiOauthTokenSecret = string.Empty;

        /// <summary>
        /// Access token
        /// </summary>
        private string apiOauthAccessKey = string.Empty;
        /// <summary>
        /// Access token secret
        /// </summary>
        private string apiOauthAccessToken = string.Empty;

        #endregion

        #region Facebook properties

        /// <summary>
        /// Gets or sets the Face Book Authorization token
        /// </summary>
        /// <remarks></remarks>
        [WebBrowsable(true),
        WebPartStorage(Storage.Shared),
        Personalizable(PersonalizationScope.Shared),
        Category("Facebook Settings"),
        WebDisplayName("Facebook Token Code"),
        WebDescription("Authorization token for the Facebook App")]
        public string FacebookTokenCode
        {
            get { return facebookTokenCode; }

            set { facebookTokenCode = value; }
        }

        /// <summary>
        /// Gets or sets the facebook user ID
        /// </summary>
        /// <remarks></remarks>
        [WebBrowsable(true),
        WebPartStorage(Storage.Shared),
        Personalizable(PersonalizationScope.Shared),
        Category("Facebook Settings"),
        WebDisplayName("Facebook User ID"),
        WebDescription("User for whose feed will be displayed on the Facebook tab.")]
        public string FacebookUserId
        {
            get { return facebookUserId; }

            set { facebookUserId = value; }
        }

        /// <summary>
        /// Gets or sets number of feeds to items to display in the webpart
        /// </summary>
        /// <remarks></remarks>
        [WebBrowsable(true),
        WebPartStorage(Storage.Shared),
        Personalizable(PersonalizationScope.Shared),
        Category("Facebook Settings"),
        WebDisplayName("Facebook Posts Count"),
        WebDescription("Number of posts to retrieve for from the User's wall post.")]
        public int FacebookPostsCount
        {
            get { return facebookPostsCount; }
            set { facebookPostsCount = value; }
        }
        #endregion

        #region Twitter Properties

        /// <summary>
        /// Gets or sets the twitter user id
        /// </summary>
        /// <remarks></remarks>
        [WebBrowsable(true),
        WebPartStorage(Storage.Shared),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("Twitter User ID"),
        Category("Twitter Settings"),
        WebDescription("User for whose tweets will be displayed on the Twitter tab.")]
        public string TwitterUserID
        {
            get { return twitterUserId; }

            set { twitterUserId = value; }
        }

        /// <summary>
        /// Gets or sets number of tweets to display in the webpart
        /// </summary>
        /// <remarks></remarks>
        [WebBrowsable(true),
        WebPartStorage(Storage.Shared),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("Twitter Posts Count"),
        Category("Twitter Settings"),
        WebDescription("Number of posts to retrieve for from the User's wall post.")]
        public int TwitterPostsCount
        {
            get { return twitterPostsCount; }
            set { twitterPostsCount = value; }
        }

        /// <summary>
        /// Gets or sets Application Token
        /// </summary>
        /// <remarks></remarks>
        [WebBrowsable(true),
        WebPartStorage(Storage.Shared),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("Application/Consumer Key"),
        Category("Twitter Settings"),
        WebDescription("Consumer Key")]
        public string APIOauthToken
        {
            get { return apiOauthToken; }
            set { apiOauthToken = value; }
        }

        /// <summary>
        /// Gets or sets Application Token
        /// </summary>
        /// <remarks></remarks>
        [WebBrowsable(true),
        WebPartStorage(Storage.Shared),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("Application/Consumer Secret Key"),
        Category("Twitter Settings"),
        WebDescription("Consumer Secret Key")]
        public string APIOauthTokenSecret
        {
            get { return apiOauthTokenSecret; }
            set { apiOauthTokenSecret = value; }
        }


        /// <summary>
        /// Gets or sets Access Token
        /// </summary>
        /// <remarks></remarks>
        [WebBrowsable(true),
        WebPartStorage(Storage.Shared),
        Personalizable(PersonalizationScope.Shared),
        Category("Twitter Settings"),
        WebDisplayName("Access Token"),
        WebDescription("Access token for the application")]
        public string APIOauthAccessKey
        {
            get { return apiOauthAccessKey; }
            set { apiOauthAccessKey = value; }
        }

        /// <summary>
        /// Gets or sets Access token secret Key
        /// </summary>
        /// <remarks></remarks>
        [WebBrowsable(true),
        WebPartStorage(Storage.Shared),
        Personalizable(PersonalizationScope.Shared),
        Category("Twitter Settings"),
        WebDisplayName("Access token secret Key"),
        WebDescription("Access Token secret key")]
        public string APIOauthAccessToken
        {
            get { return apiOauthAccessToken; }
            set { apiOauthAccessToken = value; }
        }

        #endregion

        #region Control Events
        /// <summary>
        /// Creates the child controls needed for this control
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                Controls.Add(BuildControl());
            }
            catch (Exception ex)
            {
                //Handle exception
            }
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnPreRender(EventArgs e)
        {
            //base.OnPreRender(e);
            ScriptLink.Register(this.Page, "/_layouts/SocialWebpart/Scripts/jquery-1.9.1.min.js", false);
            ScriptLink.Register(this.Page, "/_layouts/SocialWebpart/Scripts/SocialWebpart.js", false);
            CssRegistration wpCss = new CssRegistration();
            wpCss.Name = "/_layouts/1033/STYLES/SocialWebpart/socialwebpart.css";
            this.Controls.Add(wpCss);
            string[] strTabs = new string[] { "FaceBook", "Twitter" };
            if (!Page.ClientScript.IsClientScriptBlockRegistered("SocialWebParts"))
            {
                string serializedTab = (new JavaScriptSerializer()).Serialize(strTabs);
                this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SocialWebParts", string.Format("SetText('{0}');", serializedTab), true);
            }
        }
        #endregion

        #region Protected Methods
        /// <summary>
        /// This method builds the control
        /// </summary>
        /// <returns></returns>
        protected WebControl BuildControl()
        {
            WebControl control = BuildSocialControl();
            return control;
        }

        /// <summary>
        /// This method build social webpart
        /// </summary>
        /// <returns></returns>
        protected WebControl BuildSocialControl()
        {
            WebControl tabContainer = new WebControl(HtmlTextWriterTag.Div)
            {
                ID = "tabcontainer",
                CssClass = "tab-container"
            };
            try
            {
                WebControl tabText = BuildTabText();

                WebControl divClear = new WebControl(HtmlTextWriterTag.Div)
                {
                    CssClass = "clear"
                };

                WebControl divTopBorder = new WebControl(HtmlTextWriterTag.Div)
                {
                    CssClass = "tab-top-border"
                };

                WebControl divFacebook = BuildFaceBookContainer();
                WebControl divTwitter = BuildTwitterContainer();
                tabContainer.Controls.Add(tabText);
                tabContainer.Controls.Add(divClear);
                tabContainer.Controls.Add(divTopBorder);
                tabContainer.Controls.Add(divFacebook);
                tabContainer.Controls.Add(divTwitter);
            }
            catch (Exception ex)
            {
                //Handle exception
            }

            return tabContainer;
        }

        /// <summary>
        /// This method builds Tabs
        /// </summary>
        /// <returns></returns>
        protected WebControl BuildTabText()
        {
            WebControl ul = new WebControl(HtmlTextWriterTag.Ul)
            {
                CssClass = "tab-menu"
            };
            ul.Controls.Add(new Literal() { Text = "<li id='FaceBook' class='active'>FaceBook</li>" });
            ul.Controls.Add(new Literal() { Text = "<li id='Twitter'>Twitter</li>" });
            return ul;
        }

        /// <summary>
        /// This method builds Twitter container
        /// </summary>
        /// <returns></returns>
        protected WebControl BuildTwitterContainer()
        {
            TwitterFeeds feeds = new TwitterFeeds(this.APIOauthToken, this.APIOauthTokenSecret, this.APIOauthAccessKey, this.APIOauthAccessToken, this.TwitterUserID);
            WebControl twitterFeeds = feeds.GetTwitterFeeds();
            return twitterFeeds;
        }

        /// <summary>
        /// This method returns facebook feeds
        /// </summary>
        /// <returns></returns>
        protected WebControl BuildFaceBookContainer()
        {
            FaceBookFeeds feeds = new FaceBookFeeds(this.FacebookUserId, this.FacebookTokenCode, this.FacebookPostsCount);
            WebControl faceBookFeeds = feeds.GetFaceBookFeeds();
            return faceBookFeeds;
        }

        #endregion
    }
}